<script>
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  computed,
  watch,
  onUnmounted,
} from 'vue'
import * as Antd from 'ant-design-vue'
import {
  logisticsQueryRegionExtraById,
  logisticsRegionExtraSetByAdCode,
  logisticsRegionExtraAll,
} from '@Config/server/api'
import { findIndex, flattenDeep, uniq } from 'lodash'

export default defineComponent({
  props: {
    info: {
      type: Object,
      default: () => {
        return null
      },
    },
    selectedData: {
      type: Array,
      default: () => {
        return []
      },
    },

    type: {
      type: Number,
      default: 1,
    },
  },
  emits: ['select'],
  setup(props, context) {
    let info = reactive({ ...props.info })
    let treeData = reactive({ data: [] })
    let loading = ref(true)
    // let selectedData = computed(() => {
    //   return props.selectedData
    // })

    // console.log(props.fatherData, props.selectedData)

    let expandedKeys = ref([])

    //扁平化的数据
    let flattenNode = []

    //保存特殊省份，一个省份，只有一个市的情况
    let spec = [
      // {
      //   adcode: '310100', //上海城区
      //   target: '310000',
      // },
      // {
      //   adcode: '110100', //北京城区
      //   target: '110000',
      // },
      // {
      //   adcode: '120100', //天津城区
      //   target: '120000',
      // },
    ]
    let _watch = watch(
      () => props.info,
      () => {
        loading.value = true
        logisticsRegionExtraAll({
          content: props.info.adcode,
          type: props.type,
        }).then((x) => {
          loading.value = false
          treeData.data = x.data

          if (treeData.data[0].childList.length == 1) {
            spec.push({
              adcode: treeData.data[0].childList[0].adcode,
              target: treeData.data[0].adcode,
            })
          }

          flattenNode = []
          getLeafNode2(x.data[0], flattenNode)
          expandedKeys.value = [treeData.data[0].adcode]

          compareSelectedKeys()
        })
      },
      {
        deep: true,
        immediate: true,
      }
    )

    let compareSelectedKeys = () => {
      let _selected_provinces = selectedKeys.data.filter((x) =>
        /\d{2}0000$/gi.test(x)
      )
      //  console.log(_selected_provinces)

      let _selected_citys = selectedKeys.data.filter((x) =>
        /\d{4}00$/gi.test(x)
      )
      // console.log(_selected_provinces)
      // console.log(_selected_citys)

      if (_selected_provinces.length > 0) {
        selectedKeys.data = flattenNode.map((x) => x.adcode)
      }
      _selected_citys.map((x) => {
        let _flag = x.substring(0, 4)
        flattenNode.map((xx) => {
          if (xx.adcode.substring(0, 4) == _flag) {
            selectedKeys.data.push(xx.adcode)
          }
        })
      })
      selectedKeys.data = uniq(selectedKeys.data)
    }

    //只有子节点
    let getLeafNode = (_root) => {
      if (_root.childList) {
        return _root.childList.map((x) => {
          return getLeafNode(x)
        })
      } else {
        return { ..._root }
      }
    }
    //子节点和父节点
    let getLeafNode2 = (_root, _arr) => {
      if (_root.childList) {
        _arr.push({ ..._root, childList: null })
        return _root.childList.map((x) => {
          return getLeafNode2(x, _arr)
        })
      } else {
        return _arr.push({ ..._root })
      }
    }

    //只有父节点

    let getLeafNode3 = (_root, _arr) => {
      if (_root.childList) {
        _arr.push({ ..._root, childList: null })
        return _root.childList.map((x) => {
          return getLeafNode3(x, _arr)
        })
      } else {
        //  _arr.push({ ..._root, childList: null })
      }
    }
    //是否是子结点
    let isLeaf = (_list) => {
      return _list != undefined ? true : false
    }

    let checkHandler = async (checkedKeys, e) => {
      let adds = []
      let deletes = []
      if (e.checked) {
        //添加
        if (isLeaf(e.node.dataRef.childList)) {
          //父节点添加,父节点只添加自己的结点，并删除自己节点下面所有的子节点
          // console.log(
          //   '添加=' + e.node.dataRef.adcode,
          //   '删除=',
          //   getLeafNode(e.node.dataRef).map((x) => x.adcode)
          // )
          adds = [e.node.dataRef.adcode]
          deletes = getLeafNode(e.node.dataRef).map((x) => x.adcode)
          // selectedKeys.data.push(e.node.dataRef.adcode)
          // selectedKeys.data = selectedKeys.data.filter((xx) => {
          //   return getLeafNode(e.node.dataRef)
          //     .map((x) => x.adcode)
          //     .indexOf(xx)
          // })
        } else {
          //查询 checkedKeys，并归纳父子关系，如果有父子关系，则添加父，并删除此父级下面所有的子集。如果没有父子关系，则添加 checkedkeys中的子节点

          // console.log(e.node.dataRef, checkedKeys)

          let _current_city_prix = e.node.dataRef.adcode.substring(0, 4)
          let _has_all = checkedKeys.indexOf(_current_city_prix + '00') //是否选中全部
          let _delete = []
          if (_has_all >= 0) {
            //已选中了全部，则删除这个下面的所有的子集,并且只添加对应的父级
            _delete = checkedKeys.filter((x) => {
              return (
                x.substring(0, 4) == _current_city_prix &&
                x != _current_city_prix + '00'
              )
            })
            selectedKeys.data.push(_current_city_prix + '00')
            selectedKeys.data = selectedKeys.data.filter(
              (x) => _delete.indexOf(x) < 0
            )

            //  console.log('添加=', _current_city_prix + '00', '删除=', _delete)

            adds = [_current_city_prix + '00']
            deletes = _delete
          } else {
            //没有选中全部，只选中当前子结点,则添加子结点,删除半结点
            // selectedKeys.data.push(e.node.dataRef.adcode)

            // console.log('添加=', e.node.dataRef.adcode, '删除=', [])

            adds = [e.node.dataRef.adcode]
            deletes = []
          }
        }
      } else {
        //删除
        if (isLeaf(e.node.dataRef.childList)) {
          //删除父结点
          let _a = []
          getLeafNode2(e.node.dataRef, _a)
          // console.log('删除=', _a)
          //  adds = []

          deletes = _a.map((x) => x.adcode)

          spec.map((x) => {
            if (x.adcode == e.node.dataRef.adcode) {
              deletes.push(x.target)
            }
          })

          let _p = e.node.dataRef.adcode.substring(0, 2)
          adds = checkedKeys
            .filter((x) => x.substring(0, 2) == _p)
            .filter((x) => /\d{4}0{2}/gi.test(x))
        } else {
          //直接删除子节点
          let _p = e.node.dataRef.adcode.substring(0, 4)
          // console.log(
          //   '_p',
          //   _p,
          //   checkedKeys.filter((x) => x.substring(0, 4) == _p)
          // )
          adds = checkedKeys.filter((x) => x.substring(0, 4) == _p)
          deletes = [e.node.dataRef.adcode]

          // console.log('删除=', e.node.dataRef.adcode)
        }
      }
      deletes = deletes.concat(e.halfCheckedKeys)
      //  console.log(adds, deletes)
      selectedKeys.data = selectedKeys.data.concat(adds)
      selectedKeys.data = selectedKeys.data.filter((x) => {
        return deletes.indexOf(x) < 0
      })
      //console.log('添加', adds, '删除', deletes)

      compareSelectedKeys()

      // console.log(flattenNode)

      adds = flattenDeep(
        adds.map((x) => flattenNode.filter((xx) => xx.adcode == x))
      )
      deletes = flattenDeep(
        deletes.map((x) => flattenNode.filter((xx) => xx.adcode == x))
      )

      // console.log(flattenDeep(a))

      context.emit('select', {
        params: {
          nodes: [],
          checked: e.checked,
          add: adds,
          del: deletes,
          innerCallBack: (_list) => {
            //  console.log(_list)
            // console.log(_list.filter((x) => /\d{2,4}00$/gi.test(x)))
            // selectedKeys.data = _list
            //   .filter((x) => {
            //     return x.adcode.substring(0, 2) == province_prifx
            //   })
            //   .map((x) => x.adcode)
            // .filter((x) => /\d{2,4}00$/gi.test(x))
          },
        },
      })

      // return
      // // console.log(
      // //   e,
      // //   '删除=',
      // //   e.halfCheckedKeys,
      // //   e.checked ? '添加=' : '删除=',
      // //   e.node.dataRef
      // // )

      // // 删除半节点
      // selectedKeys.data = selectedKeys.data.filter(
      //   (xx) => e.halfCheckedKeys.indexOf(xx) < 0
      // )
      // let _external_remove = []
      // if (e.checked) {
      //   let _a = []
      //   getLeafNode2(e.node.dataRef, _a)
      //   _a = _a.map((x) => x.adcode)
      //   selectedKeys.data = [...selectedKeys.data, ..._a]

      //   let pAndC = e.checkedNodes.filter((x) => /\d{2,4}0{2,4}$/gi.test(x.key))
      //   pAndC.map((x) => {
      //     if (selectedKeys.data.indexOf(x.key) < 0) {
      //       selectedKeys.data.push(x.key)
      //     }
      //   })
      //   _external_remove = []
      // } else {
      //   let _a = []
      //   getLeafNode2(e.node.dataRef, _a)
      //   _a = _a.map((x) => x.adcode)

      //   selectedKeys.data = selectedKeys.data.filter((x) => _a.indexOf(x) < 0)
      //   _external_remove = _a
      // }

      // // console.log(
      // //   '添加=',
      // //   selectedKeys.data,
      // //   '删除=',
      // //   e.halfCheckedKeys.concat(_external_remove)
      // // )

      // let _citys_prix = selectedKeys.data
      //   .filter((x) => /\d{4}0{2}$/gi.test(x))
      //   .map((xxx) => {
      //     return xxx.substring(0, 4)
      //   })

      // let g = selectedKeys.data.filter((xx) => {
      //   if (xx.substring(4, 6) == '00') return true

      //   return _citys_prix.indexOf(xx.substring(0, 4)) < 0
      // })
      // console.log(g)

      // // if (e.checked) {
      // //   //添加
      // //   // let _s = []
      // //   //  getLeafNode3(e.node.dataRef, _s)
      // //   selectedKeys.data.push(e.node.dataRef.adcode)
      // //   //检查e.checkedNodes表中，是否有省省、市的adcode在selectedKeys中不存在,如果有，需要添加到selectedKeys.data中

      // //   let pAndC = e.checkedNodes.filter((x) => /\d{2,4}0{2,4}$/gi.test(x.key))
      // //   pAndC.map((x) => {
      // //     if (selectedKeys.data.indexOf(x.key) < 0) {
      // //       selectedKeys.data.push(x.key)
      // //     }
      // //   })
      // // } else {
      // //   //删除

      // //   let _the_node = []
      // //   getLeafNode2(e.node.dataRef, _the_node)
      // //   selectedKeys.data = selectedKeys.data.filter(
      // //     (xx) => _the_node.map((x) => x.adcode).indexOf(xx) < 0
      // //   )
      // // }

      // // return

      // // flattenNode.map((x) => {
      // //   console.log(
      // //     x.adcode,
      // //     e.halfCheckedKeys[0],
      // //     x.adcode == e.halfCheckedKeys[0]
      // //   )
      // // })
      // // console.log(
      // //   '添加=',
      // //   e.checkedNodes.map((x) => x.key).filter((x) => /\d{2,4}00$/gi.test(x)),
      // //   '删除=',
      // //   uniq(_provinceAndCity.concat(e.halfCheckedKeys))
      // //
      // // console.log(e)

      // return

      // let dataRef = e.node.dataRef
      // let nodes = flattenDeep([getLeafNode(dataRef)])
      // let province_prifx = props.info.adcode.substring(0, 2)

      // context.emit('select', {
      //   params: {
      //     nodes: nodes,
      //     checked: e.checked,

      //     innerCallBack: (_list) => {
      //       // console.log(_list.filter((x) => /\d{2,4}00$/gi.test(x)))
      //       selectedKeys.data = _list
      //         .filter((x) => {
      //           return x.adcode.substring(0, 2) == province_prifx
      //         })
      //         .map((x) => x.adcode)
      //       // .filter((x) => /\d{2,4}00$/gi.test(x))
      //     },
      //   },
      // })

      // //省份、市选中的
    }

    let selectedKeys = reactive({ data: [] })
    //    selectedKeys.data = props.selectedData.map((x) => x.adcode)

    let _watch2 = watch(
      () => props.selectedData,
      () => {
        // console.log(
        //   props.selectedData
        //     .map((x) => x.adcode)
        //     .filter((x) => !/\d{2,4}00$/gi.test(x))
        // )
        selectedKeys.data = props.selectedData.map((x) => x.adcode)
        //  console.log(selectedKeys.data)

        // .filter((x) => !/\d{2,4}00$/gi.test(x))
      },
      {
        deep: true,
        immediate: true,
      }
    )

    onUnmounted(() => {
      _watch2()
      _watch()
    })

    let expandHandler = (_expandedKeys) => {
      expandedKeys.value = _expandedKeys
    }

    //省份、市选中的
    // _provinceAndCity = selectedKeys.data
    //   .map((x) => x.key)
    //   .filter((x) => /\d{2,4}00$/gi.test(x))

    // watch(
    //   () => {
    //     return selectedKeys?.data
    //   },
    //   () => {
    //     compareSelectedKeys()
    //   }
    // )

    let tree = ref()
    return {
      treeData,
      checkHandler,
      selectedKeys,
      loading,
      expandedKeys,
      expandHandler,
      tree,
      props,
    }
  },
  render() {
    return this.loading ? (
      <Antd.Spin tip="加载数据中..." />
    ) : (
      <div>
        <Antd.Tree
          expandedKeys={this.expandedKeys}
          checkedKeys={this.selectedKeys.data}
          selectable={false}
          replaceFields={{
            children: 'childList',
            title: 'name',
            key: 'adcode',
          }}
          checkable={true}
          treeData={this.treeData.data}
          onCheck={this.checkHandler}
          onExpand={this.expandHandler}
          class="scopeTree"
          ref="tree"
        ></Antd.Tree>
      </div>
    )
  },
})
</script>
<style>
.ant-tree-child-tree {
  display: flex !important;
  flex-wrap: wrap;
}
.ant-tree-child-tree .ant-tree-child-tree {
  border: 1px solid rgba(120, 120, 120, 0.3);
}
.ant-tree-child-tree > li {
  min-width: 120px;
}
</style>
